import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  DownOutlined,
  PlusOutlined,
  UpOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Row,
  Col,
  Card,
  Input,
  Button,
  Dropdown,
  Menu,
  Modal,
  message,
  Divider,
  DatePicker,
} from 'antd';
import moment from 'moment';
import router from 'umi/router';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Authorized from '@/utils/Authorized';
import styles from '@/utils/utils.less';
import { checkPermissions } from '@/utils/authority';
import Area from '../../components/Area';
import DictCode from '../../components/DictCode';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;

@connect(({ detexport, loading }) => ({
  data: detexport.data,
  loading: loading.models.detexport,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      expandForm: false,
      selectedRows: [],
      selectedRowKeys: [],
    };

    this.tableSearchLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
  }

  componentDidMount() {
    this.getList();
  }

  // 获取列表
  getList = (currentPage = 1, pageSize = 10, isClear = true) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formFieldsValue = {};
      Object.keys(fieldsValue).forEach(key => {
        if (key === 'ass' && fieldsValue[key]) {
          // eslint-disable-next-line no-param-reassign
          fieldsValue[key] = fieldsValue[key].join(',');
        }
        if (key === 'creTime') {
          // eslint-disable-next-line no-unused-expressions
          (formFieldsValue.startDate = fieldsValue.creTime
            ? fieldsValue.creTime[0].format('YYYY-MM-DD')
            : // eslint-disable-next-line no-sequences
              null),
            (formFieldsValue.endDate = fieldsValue.creTime
              ? fieldsValue.creTime[1].format('YYYY-MM-DD')
              : null);
        }
        formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key];
        delete formFieldsValue.creTime;
      });
      const pagerArg = { currentPage, pageSize };
      const values = {
        declDetailVo: { ...formFieldsValue },
        pagerArg,
      };
      dispatch({
        type: 'detexport/fetchDetExpLList',
        payload: {
          ...values,
        },
      });
    });
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { expandForm } = this.state;
    this.setState({
      expandForm: !expandForm,
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize, false);
  };

  // 重置
  resetSearch = () => {
    const { form } = this.props;
    // eslint-disable-next-line no-unused-vars
    const { activeKey } = this.state;
    form.resetFields();
    form.setFieldsValue({
      creTime: null,
    });
  };

  // 删除数据
  delete = record => {
    const {
      dispatch,
      data: {
        pagination: { current, pageSize, total },
      },
    } = this.props;
    this.handleSelectRows([record], [record.declDetailId]);
    Modal.confirm({
      title: `你确定要删除"${record.declDetailName}"明细表吗？`,
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'detexport/delDet',
          payload: { declDetailId: record.declDetailId, vno: record.vno },
          callback: res => {
            if (res.success) {
              const selectedLen = 1;
              if (current > 1 && (total % pageSize === selectedLen || pageSize === selectedLen)) {
                this.getList(current - 1, pageSize);
              } else {
                this.getList(current, pageSize);
              }
              this.setState({ selectedRowKeys: [] });
              message.success('删除成功！');
            } else {
              message.warning(`${res.message || '删除失败'}`);
            }
          },
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  // 修改
  update = suppProtId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'detexport/fetchDetail',
      payload: { suppProtId },
      callback: response => {
        const areaIdList = [];
        response.areaList.forEach(item => {
          areaIdList.push(item.areaId);
        });
        this.getProductList(response.recvSuppId, areaIdList);
        dispatch({
          type: 'publicdata/getCustList',
          payload: [{ custId: response.custId, name: response.custName }],
        });
        dispatch({
          type: 'publicdata/getAreaList',
          payload: response.areaList,
        });
        this.handleModalVisible(true);
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="名称" {...this.tableSearchLayout}>
              {getFieldDecorator('declDetailName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="执行地" {...this.tableSearchLayout}>
              {getFieldDecorator('areaId')(<Area allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={() => this.getList()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="名称" {...this.tableSearchLayout}>
              {getFieldDecorator('declDetailName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="执行地" {...this.tableSearchLayout}>
              {getFieldDecorator('areaId')(<Area allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="险种" {...this.tableSearchLayout}>
              {getFieldDecorator('ass')(
                <DictCode dictType="INS_ACCU_SELF" mode="multiple" allowClear />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="创建人" {...this.tableSearchLayout}>
              {getFieldDecorator('creName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="创建日期" {...this.tableSearchLayout}>
              {getFieldDecorator('creTime')(
                <RangePicker
                  placeholder={['创建开始日期', '创建结束日期']}
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD"
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <div style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" onClick={() => this.getList()}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起
                  <UpOutlined />
                </a>
              </div>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.state;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  render() {
    const { data, loading } = this.props;
    const { selectedRows, selectedRowKeys } = this.state;
    const columns = [
      {
        title: '名称',
        dataIndex: 'declDetailName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '执行地',
        dataIndex: 'areaName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '险种',
        dataIndex: 'assName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '类型',
        dataIndex: 'typeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '创建人',
        dataIndex: 'creName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '创建日期',
        dataIndex: 'creTime',
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        render: val => moment(val).format('YYYY-MM-DD HH:mm'),
      },
      {
        title: '操作',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <div>
            <a
              onClick={() =>
                router.push(`/systemsetting/detexport/detail?declDetailId=${record.declDetailId}`)
              }
            >
              查看
            </a>
            <Divider type="vertical" />
            <Dropdown
              overlay={
                <Menu>
                  {checkPermissions('mgr:declDetail:updateDeclDet') && (
                    <Menu.Item
                      key="update"
                      onClick={() =>
                        router.push(
                          `/systemsetting/detexport/update?declDetailId=${record.declDetailId}`
                        )
                      }
                    >
                      修改
                    </Menu.Item>
                  )}
                  {checkPermissions('mgr:declDetail:delDeclDet') && (
                    <Menu.Item key="updateStatus" onClick={() => this.delete(record)}>
                      删除
                    </Menu.Item>
                  )}
                </Menu>
              }
            >
              <a>
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </div>
        ),
      },
    ];
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tableCard}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Authorized authority="mgr:declDetail:insertDeclDet" noMatch={null}>
                <Button
                  icon={<PlusOutlined />}
                  type="primary"
                  onClick={() => router.push(`/systemsetting/detexport/add`)}
                >
                  新增
                </Button>
              </Authorized>
            </div>
            <StandardTable
              selectedRows={selectedRows}
              selectedRowKeys={selectedRowKeys}
              loading={loading}
              data={data}
              rowKey="declDetailId"
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default TableList;
